import elementResizeDetectorMaker from "element-resize-detector";

let observer
const oldValue = {
  width: 0,
  height: 0
}
const resizeListen = {
  mounted(el, binding) {
    observer = elementResizeDetectorMaker()
    observer.listenTo(el, function (element) {
      const width = element.offsetWidth;
      const height = element.offsetHeight;
      if (oldValue.width !== width || oldValue.height !== height) { // 数值重复不回调值
        oldValue.width = width
        oldValue.height = height
        // v-resizeListen="xx" 其中 xx 对应 binding.value
        // 1.若xx是 数值，则binding.value是个数
        // 2.若xx是 函数，则binding.value是个方法
        // binding.value(yy) 调用xx方法，并把yy当参数传出
        binding.value(oldValue)
      }
    })
  },
  unmounted(el) {
    if (observer) {
      observer.removeListener(el)
    }
  }
}

export default resizeListen